<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :showCollapse="false"
      :searchNum="searchItemCount"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      
      @submit="searchFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="compCname" label="页面名称">
          <FIInput v-model="state.query.compCname" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="页面收藏管理列表"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="compEname"
      :rowNo="true"
      v-model:columns="columns"
      :insertable="false"
      deletable
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :showSaveModel="false"
      :draggableRow="true"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="actionClick"
      @row-delete="deleteRow"
      @row-drag="rowDrag"
    >
      <template #headerBtn>
        <FIButton @click="menuShow = true" border>新增</FIButton>
        <!-- <FIPopconfirmBtn
          title="您是否确认删除选中数据吗？"
          buttonText="删除"
          beforePopText="请选择一条数据"
          :btn-binds="{ id: 'delete', border: true }"
          @confirm="deleteRow"
        >
        </FIPopconfirmBtn> -->
        <!-- <FIButton id="export_usersAudit" class="margin-left5" @click="exportRow"></FIButton> -->
      </template>
    </FITable>
    <FIModel v-model="menuShow" width="700" title="新增收藏" @close="menuShow = false" @confirm="saveMenuFunc">
      <el-row :gutter="20">
        <el-col :span="24">
          <FIFormItem prop="formEname" label="菜单树列表">
            <menu-list
              @select-node="selectNode"
              style="width: 400px; height: 600px; overflow: auto"
              :buttonPage_Ckeck="false"
              :button_noCheck="false"
              type="menu"
            ></menu-list>
          </FIFormItem>
        </el-col>
      </el-row>
    </FIModel>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import menuList from '../../user/authorityMaint/components/menuList'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage, useMessageBox } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import {
  apipageFavorQuery,
  apipageFavorDelete,
  apipageFavorInsert,
  apiExchangeSortIndex,
} from '@/api/configEnvMaint/index.ts'
const route = useRoute()
const menuShow = ref(false)
const searchWrapperSpan = 8
const showSearch = ref(true)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'pageFavor'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)

const state = reactive({
  query: {
    compCname: '',
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const columns: Column[] = reactive([
  // {
  //   label: '序号',
  //   prop: 'loginName',
  //   align: 'center',
  //   editType: 'input',
  //   editable: true,
  //   sortable: true,
  //   // filterable: true,
  //   readonly: true,

  //   modelValue: {
  //     inputValue: '',
  //     isBlank: false,
  //     notBlank: false,
  //   },
  // },
  {
    label: '页面名称',
    prop: 'compCname',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '菜单路径',
    prop: 'compPath',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '收藏时间',
    prop: 'recCreateTime',
    align: 'center',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '',
    prop: 'action',
    actionConfig: [{ id: 'isTop', type: 'top' }],
  },
])

const checkedRows = ref([])
const treeVal = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const selectNode = (data) => {
  treeVal.value = data

  // searchFn('query','',data.payload.nodeId)
}
const rowDrag = (newData,oldData) =>{
  console.log(state.dataList[newData].id,'数据')
  apiExchangeSortIndex([state.dataList[newData].id, state.dataList[oldData].id])
    .then((res) => {
      console.log(res, 'res123')
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn()
      } else {
      }
    })
    .catch((error: any) => {})
}
const saveMenuFunc = () => {
  console.log(treeVal, 'treeVal')
  let list = treeVal.value.map((v) => {
    if (v.payload.nodeType == 1) {
      return v.payload.nodeEname
    }
  })
  console.log(list, 'list')
  let newArr = list.filter((item) => item && item.trim())
  console.log(newArr, 'newArr')
  apipageFavorInsert(newArr)
    .then((res) => {
      if (res.data.success) {
        useMessage().success(res.data.message)

        menuShow.value = false
        searchFn()
        // searchFn('query','',activeName.value == '3' ? editData.value.postId : editData.value.groupId)
      }
    })
    .catch((error: any) => {})
}
//删除事件
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.compEname) ids.push(item?.compEname)
    })
  isTableLoading.value = true
  apipageFavorDelete(ids)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn()
      }
    })
    .catch((error: any) => {
      useMessage().error(error.data.message)
      isTableLoading.value = false
    })
}
//操作
const actionClick = (item, rowData, btnInfo) => {
  console.log(rowData, 'rowData')
  useMessageBox()
    .confirm(`您确认要置顶吗？`, '提示')
    .then(() => {
      apiExchangeSortIndex([rowData.id, 0])
        .then((res) => {
          console.log(res, 'res123')
          if (res.data.success) {
            useMessage().success(res.data.message)
            searchFn()
          } else {
          }
        })
        .catch((error: any) => {})
    })
    .catch(() => {})
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  apipageFavorQuery(state.query)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        // console.log(state.dataList)
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
//   const exportRow = () => {
//     apiGroupUserExport(state.query)
//   }
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
onMounted(() => {
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped></style>
